<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { DepartmentCheckReportApi, ClassCheckReportApi } from '@/api/table'
import { ref, unref, reactive } from 'vue'
import { useTable } from '@/hooks/web/useTable'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { BaseButton } from '@/components/Button'
import type { DepartmentItem } from '@/api/department/types'
import { getTreeDepartmentsApi } from '@/api/department'
import * as XLSX from 'xlsx'
import { useButtonPermiss } from '@/utils/buttonpermiss'

import { getProblemTypesApi } from '@/api/role'
import WorkType from './components/WorkType.vue'
import {
  ElTabs,
  ElTabPane,
  ElProgress,
  TabsPaneContext,
  ElForm,
  ElFormItem,
  ElSelect,
  ElOption,
  ElDatePicker,
  ElInput,
  ElMessage,
  ElButton,
  ElTreeSelect
} from 'element-plus'
import { useUserStoreWithOut } from '@/store/modules/user'
const userStore = useUserStoreWithOut()
const activeName = ref('first')
const haspermiss = ref<String[]>([])
const getUseButtonPermiss = () => {
  useButtonPermiss().then((res) => {
    haspermiss.value = res
  })
}
getUseButtonPermiss()
const { t } = useI18n()
const handleClick = (name) => {
  console.log(name)
  activeName.value = name
  getList()
}
const currentDay = new Date()
function getFormattedDate(date) {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}
const fifteenDaysAgo = new Date()
fifteenDaysAgo.setDate(fifteenDaysAgo.getDate() - 30)
const v = ref([
  getFormattedDate(fifteenDaysAgo) + ' 00:00:00',
  getFormattedDate(currentDay) + ' 23:59:59'
])
const columns: TableColumn[] = [
  {
    field: 'index',
    label: t('userDemo.index'),
    type: 'index'
  },
  {
    field: 'depNo',
    label: t('userDemo.depNo')
  },
  {
    field: 'depName',
    label: t('userDemo.departmentName')
  },
  {
    field: 'userNo',
    label: t('userDemo.userNo')
  },
  {
    field: 'userName',
    label: t('userDemo.username')
  },

  {
    field: 'videoCount',
    label: '视频数量'
  },
  //   {
  //     field: 'videoLength',
  //     label: '视频长度'
  //   },
  //   {
  //     field: 'videoSize',
  //     label: '视频大小'
  //   },
  {
    field: 'audioCount',
    label: '音频数量'
  },
  //   {
  //     field: 'audioSize',
  //     label: '音频大小'
  //   },
  {
    field: 'imageCount',
    label: '图片数量'
  },
  //   {
  //     field: 'imageSize',
  //     label: '图片大小'
  //   },
  {
    field: 'logCount',
    label: '日志数量'
  }
  //   {
  //     field: 'logSize',
  //     label: '日志大小'
  //   }
]
const columns1: TableColumn[] = [
  {
    field: 'problemTypeName',
    label: '证据类型'
  },
  {
    field: 'depNo',
    label: t('userDemo.depNo')
  },
  {
    field: 'depName',
    label: t('userDemo.departmentName')
  },

  {
    field: 'videoCount',
    label: '视频数量'
  },
  {
    field: 'videoLength',
    label: '视频长度'
  },
  //   {
  //     field: 'videoSize',
  //     label: '视频大小'
  //   },
  {
    field: 'audioCount',
    label: '音频数量'
  },
  //   {
  //     field: 'audioSize',
  //     label: '音频大小'
  //   },
  {
    field: 'imageCount',
    label: '图片数量'
  },
  //   {
  //     field: 'imageSize',
  //     label: '图片大小'
  //   },
  {
    field: 'logCount',
    label: '日志数量'
  }
  //   {
  //     field: 'logSize',
  //     label: '日志大小'
  //   },
  //   {
  //     field: 'noLengthCount',
  //     label: '视频时长不达标'
  //   },
  //   {
  //     field: 'noCapacityCount',
  //     label: '视频容量不达标'
  //   },
  //   {
  //     field: 'usingRate',
  //     label: '使用率'
  //   },
  //   {
  //     field: 'deviceAlarmCount',
  //     label: '异常告警'
  //   }
]
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    // const { pageSize, currentPage } = tableState
    let res
    if (activeName.value == 'first') {
      res = await DepartmentCheckReportApi({
        // pageNo: unref(currentPage),
        // pageRow: unref(pageSize),
        // pageModel: { ...unref(searchParams) }
        ...unref(searchParams)
      })
    } else {
      res = await ClassCheckReportApi({
        // pageNo: unref(currentPage),
        // pageRow: unref(pageSize),
        // pageModel: { ...unref(searchParams) }
        ...unref(searchParams)
      })
    }

    const list = res.data || []

    return {
      list: list,
      total: res.data.totalCount || 0
    }
  }
})
const departmentList = ref<DepartmentItem[]>([])
const fetchDepartment = async () => {
  const res = await getTreeDepartmentsApi({})
  departmentList.value = res.data
}
fetchDepartment()
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, getElTableExpose, delList } = tableMethods
const searchParams = ref({ startTime: v.value[0], endTime: v.value[1] })
const setSearchParams = (params: any) => {
  if (params.date) {
    params.startTime = params.date[0]
    params.endTime = params.date[1]
    delete params.date
  }
  searchParams.value = params
  getList()
}
const searchSchema = reactive<FormSchema[]>([
  {
    field: 'depGuid',
    label: t('userDemo.department'),
    component: 'TreeSelect',
    componentProps: {
      nodeKey: 'guid',
      props: {
        label: 'depName',
        value: 'guid',
        children: 'children'
      },
      placeholder: '请选择部门',
      highlightCurrent: true,
      expandOnClickNode: false,
      checkStrictly: true,
      checkOnClickNode: true,
      clearable: true
    },
    optionApi: async () => {
      return departmentList.value || []
    }
  },

  //   {
  //     field: 'userNoOrName',
  //     label: '用户',
  //     component: 'Input',
  //     componentProps: {
  //       placeholder: '请输入用户编号或名称'
  //     }
  //   },
  {
    field: 'date',
    label: t('problem.time'),
    component: 'DatePicker',
    componentProps: {
      style: { width: '340px' },
      type: 'datetimerange',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      StartPlaceholder: 'Start date',
      EndPlaceholder: 'End date'
    }
  }
])
const searchSchema1 = reactive<FormSchema[]>([
  {
    field: 'depGuid',
    label: t('userDemo.department'),
    component: 'TreeSelect',
    componentProps: {
      nodeKey: 'guid',
      props: {
        label: 'depName',
        value: 'guid',
        children: 'children'
      },
      placeholder: '请选择部门',
      highlightCurrent: true,
      expandOnClickNode: false,
      checkStrictly: true,
      checkOnClickNode: true,
      clearable: true
    },
    optionApi: async () => {
      return departmentList.value || []
    }
  },
  {
    field: 'problemType',
    label: '证据类型',
    component: 'Select',
    componentProps: {
      clearable: true,
      filterable: true,
      props: {
        label: 'typeName',
        // value: 'guid'
        value: 'guid'
      }
    },
    optionApi: async () => {
      const res = await getProblemTypesApi({ pageFlag: false })
      return res.data || []
    }
  },
  {
    field: 'date',
    label: t('problem.time'),
    component: 'DatePicker',
    componentProps: {
      style: { width: '340px' },
      type: 'datetimerange',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      StartPlaceholder: 'Start date',
      EndPlaceholder: 'End date'
    }
  }
])
interface tableExpose {
  部门编号: string
  部门名称: string
  用户编号: string
  用户名: string
  视频数量: string
  视频长度?: string
  视频大小?: string
  音频数量: string
  音频大小?: string
  图片数量: string
  图片大小?: string
  日志数量: string
  日志大小?: string
  视频时长不达标?: number
  视频容量不达标?: number
  使用率?: string
  异常告警?: number
}

const handleData = async () => {
  let arr: tableExpose[] = []

  const res = await DepartmentCheckReportApi({
    pageFlag: false,
    pageModel: { ...unref(searchParams) }
  })
  const list = res.data.pageModels
  list.map((item) => {
    arr.push({
      部门编号: item.depNo,
      部门名称: item.depName,
      用户编号: item.userNo,
      用户名: item.userName,
      视频数量: item.videoCount,
      //   视频长度: item.videoLength,
      //   视频大小: item.videoSize,
      音频数量: item.audioCount,
      //   音频大小: item.audioSize,
      图片数量: item.imageCount,
      //   图片大小: item.imageSize,
      日志数量: item.logCount
      //   日志大小: item.logSize
    })
  })
  return arr
}
const handleData1 = async () => {
  let arr: tableExpose[] = []

  const res = await ClassCheckReportApi({
    pageFlag: false,
    pageModel: { ...unref(searchParams) }
  })
  const list = res.data.pageModels
  list.map((item) => {
    arr.push({
      部门编号: item.depNo,
      部门名称: item.depName,
      用户编号: item.userNo,
      用户名: item.userName,
      视频数量: item.videoCount,
      //   视频长度: item.videoLength,
      //   视频大小: item.videoSize,
      音频数量: item.audioCount,
      //   音频大小: item.audioSize,
      图片数量: item.imageCount,
      //   图片大小: item.imageSize,
      日志数量: item.logCount
      //   日志大小: item.logSize,
      //   视频时长不达标: item.noLengthCount,
      //   视频容量不达标: item.noCapacityCount,
      //   使用率: item.usingRate,
      //   异常告警: item.deviceAlarmCount
    })
  })
  return arr
}
const exportToExcel = async () => {
  // 创建一个工作簿
  const workbook = XLSX.utils.book_new()
  // 创建一个工作表
  const worksheet = XLSX.utils.json_to_sheet(await handleData())

  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')

  // 生成Excel文件
  XLSX.writeFile(workbook, '部门考核.xlsx')
}
const exportToExcel1 = async () => {
  // 创建一个工作簿
  const workbook = XLSX.utils.book_new()
  // 创建一个工作表
  const worksheet = XLSX.utils.json_to_sheet(await handleData1())

  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')

  // 生成Excel文件
  XLSX.writeFile(workbook, '分类考核.xlsx')
}
const props = {
  label: 'depName',
  value: 'guid',
  children: 'children'
}
const handleChange = (value: any) => {
  console.log(value)
  searchParams.value.depGuid = value
}
const resetForm = () => {
  searchParams.value = {}
  getList()
}
const searchKeys = reactive({
  depGuid: '',
  userNoOrName: '',
  startTime: '',
  endTime: ''
})

const onSubmit = () => {
  searchParams.value = { ...searchKeys, startTime: v.value[0], endTime: v.value[1] }
  getList()
}
</script>

<template>
  <ContentWrap>
    <el-tabs v-model="activeName" class="demo-tabs" @tab-change="handleClick">
      <el-tab-pane label="单位考核" name="first">
        <!-- <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" /> -->
        <el-form :model="searchKeys" :inline="true">
          <el-form-item label="所属部门" style="width: 260px">
            <el-tree-select
              v-model="searchKeys.depGuid"
              :data="departmentList"
              :props="props"
              placeholder="请选请选择部门"
              filterable
              clearable
              @change="handleChange"
            />
          </el-form-item>
          <el-form-item label="用户">
            <el-input v-model="searchKeys.userNoOrName" placeholder="请输入用户名称或编号" />
          </el-form-item>
          <el-form-item label="日期筛选">
            <el-date-picker
              v-model="v"
              type="datetimerange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD HH:mm:ss"
              date-format="YYYY-MM-DD ddd"
              time-format="A hh:mm:ss"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
          </el-form-item>
        </el-form>
        <div
          style="display: flex; justify-content: end; margin-top: -50px; margin-bottom: 10px"
          v-if="haspermiss.includes('导出')"
        >
          <BaseButton type="primary" @click="exportToExcel">{{
            t('exampleDemo.exprot')
          }}</BaseButton>
        </div>
        <Table
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :reserveIndex="true"
          :columns="columns"
          :data="dataList"
          :loading="loading"
          :pagination="{
            total
          }"
          @register="tableRegister"
        />
      </el-tab-pane>
      <el-tab-pane label="分类考核" name="second">
        <!-- <Search :schema="searchSchema1" @reset="setSearchParams" @search="setSearchParams" /> -->
        <el-form :inline="true">
          <el-form-item label="日期筛选">
            <el-date-picker
              v-model="v"
              type="datetimerange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD HH:mm:ss"
              date-format="YYYY-MM-DD ddd"
              time-format="A hh:mm:ss"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
          </el-form-item>
        </el-form>
        <div
          style="display: flex; justify-content: end; margin-top: -50px; margin-bottom: 10px"
          v-if="haspermiss.includes('导出')"
        >
          <BaseButton type="primary" @click="exportToExcel1">{{
            t('exampleDemo.exprot')
          }}</BaseButton>
        </div>
        <Table
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :reserveIndex="true"
          :columns="columns1"
          :data="dataList"
          :loading="loading"
          @register="tableRegister"
          :pagination="{
            total
          }"
        />
      </el-tab-pane>
      <!-- <el-tab-pane label="作业类型情况统计" name="three">
        <WorkType />
      </el-tab-pane> -->
      <!-- <el-tab-pane label="用户考核" name="three" /> -->
    </el-tabs>

    <!-- :text-preview="['filePath']" -->
  </ContentWrap>
</template>
